/* eslint-disable @typescript-eslint/no-unused-expressions */
// 封装的具有解决中文输入异常问题的Input组件
import { Input } from 'antd';
import React, { useEffect, useRef } from 'react';

export default (props: any) => {
  const { value, onChange, ...setProps } = props;
  // 增加一个ref记录输入框的值，继承父组件的value
  const inputRef = useRef<HTMLInputElement>(null);
  const compositionRef = useRef<boolean>(false);

  useEffect(() => {
    if (inputRef.current) {
      // 接受父组件传来的value
      inputRef.current.value = value || '';
    }
  }, [value]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!compositionRef.current) {
      // 执行父组件的change事件
      onChange && onChange(e);
    }
  };

  const Composition = (e: React.CompositionEvent<HTMLInputElement>) => {
    if (e.type === 'compositionend') {
      compositionRef.current = false;
      // 执行父组件的change事件
      onChange && onChange(e);
    } else {
      compositionRef.current = true;
    }
  };
  return (
    <Input
      ref={inputRef}
      onChange={handleChange}
      onCompositionStart={Composition}
      onCompositionEnd={Composition}
      onCompositionUpdate={Composition}
      {...setProps}
    />
  );
};
